<!--
 * @Author: Dorange.Wang
 * @Date: 2021-05-17 14:53:13
 * @LastEditors: your name
 * @LastEditTime: 2021-09-24 10:25:53
 * @Description: file content
-->
<route>
{
  "meta":{
    "title":"第三方服务",
    "showMenu":true,
    "serialNum": 32
  }
}
</route>

<template>
  <div>
    <el-row :gutter="12">
      <el-col :span="6">
        <el-input
          v-model="queryData.key"
          placeholder="服务Key"
          clearable
          :maxlength="28"
          prefix-icon="el-icon-search"
        />
      </el-col>

      <el-col :span="6">
        <el-input
          v-model="queryData.searchKey"
          placeholder="服务Key或服务名称"
          clearable
          :maxlength="64"
          prefix-icon="el-icon-search"
        />
      </el-col>

      <el-col :span="6">
        <el-button type="primary" @click="loadData(1)">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-col>

      <el-col :span="24" class="mt10">
        <DropdownButtons
          :buttons="[
            {
              icon: 'el-icon-circle-plus-outline',
              command: 'service',
              title: '新建服务',
            },
            {
              icon: 'el-icon-upload2',
              command: 'importService',
              title: '导入服务',
              upload: {
                accept: '.hm_service',
                httpRequest: handleHttpRequest,
              },
            },
          ]"
          @command="handleCreate"
        />
      </el-col>
    </el-row>
    <el-table
      class="mt10 ds-table"
      :data="tableData"
      v-loading="loading"
      style="width: 100%"
      current-row-key="id"
      stripe
      border
    >
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row :gutter="12">
            <el-col
              :span="8"
              v-for="item in scope.row.settingList"
              :key="item.env"
            >
              <el-card class="mb10" v-if="getEnvActive(item)" shadow="never">
                <div class="ds-table_env-title">
                  <i
                    class="dymIcon"
                    :class="
                      item.type === 'CLOUD'
                        ? 'el-icon-cloudy'
                        : 'el-icon-map-location'
                    "
                  ></i
                  >{{ getEnvName(item) }}
                </div>

                <el-form inline class="ds-table_env-info">
                  <el-form-item label="服务地址">
                    {{ item.serverUrl }}
                  </el-form-item>
                  <template v-if="scope.row.authType === 'TOKEN'">
                    <el-form-item label="认证地址">
                      <el-tag class="mr5" type="info" size="mini">{{
                        item.tokenMethod
                      }}</el-tag>
                      {{ item.tokenUrl }}
                    </el-form-item>
                    <el-form-item label="TOKEN取值">
                      {{ item.tokenPath }}
                    </el-form-item>
                    <el-form-item label="TOKEN有效期">
                      {{ item.tokenExpire }}
                    </el-form-item>
                  </template>
                </el-form>

                <ParamsTable
                  class="mt10"
                  v-if="scope.row.authType !== 'NONE'"
                  :tableData="item.params"
                />
              </el-card>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column prop="key" label="服务Key">
        <template slot-scope="scope">
          {{ scope.row.key }}
          <el-button
            style="margin-left: 10px"
            type="text"
            @click="copy(scope.row.key)"
            icon="el-icon-document-copy"
          ></el-button>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="服务名称" />
      <el-table-column prop="authType" label="认证方式" width="200">
        <template slot-scope="scope">
          {{ scope.row.authType | authType }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="服务描述" />
      <el-table-column prop="modifyDate" label="更新时间" width="200">
        <template slot-scope="scope">
          {{ scope.row.modifyDate | moment }}
        </template>
      </el-table-column>
      <el-table-column prop="actions" label="操作" width="150">
        <template slot-scope="scope">
          <span class="table-actionItem"
            ><el-button type="text" @click="handleEdit(scope.row)"
              >编辑</el-button
            ></span
          >
          <span class="table-actionItem">
            <el-popconfirm
              title="确定要删除该服务吗？"
              placement="top"
              @confirm="handleDelete(scope.row)"
            >
              <el-button class="link-danger" type="text" slot="reference"
                >删除</el-button
              >
            </el-popconfirm>
          </span>
          <span class="table-actionItem"
            ><el-button type="text" @click="handleExport(scope.row)"
              >导出</el-button
            ></span
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="tr mt24">
      <x-pagination
        :total="total"
        :pageSize.sync="pageData.pageSize"
        :pageNo.sync="pageData.pageNo"
        @search="loadData()"
      />
    </div>

    <HttpServiceForm ref="HttpServiceForm" />
  </div>
</template>

<script>
import {
  getHmhttpservicePageList,
  deleteHmhttpservice,
  getHmhttpserviceExport,
  postHmhttpserviceImport,
} from "@/apis/paas/HmHttpServiceController.js"
import { getHmenvironmentList } from "@/apis/paas/HmEnvironmentController.js"
import HttpServiceForm from "./__components__/HttpServiceForm"
import ParamsTable from "./__components__/ParamsTable"
import { copy, exportAppDataFromJson } from "@/utils/util"
import DropdownButtons from "@/components/DropdownButtons/Index.vue"
import { cloneDeep } from "lodash"
export default {
  name: "HttpService",
  components: {
    HttpServiceForm,
    ParamsTable,
    DropdownButtons,
  },

  data() {
    return {
      copy,
      loading: false,
      envConfigList: [], // 系统显示的环境
      queryData: {},
      pageData: {
        pageSize: 10,
        pageNo: 1,
      },
      tableData: [],
      total: 0,
    }
  },

  created() {
    this.loadAllData()
  },

  methods: {
    async loadAllData() {
      this.envConfigList = await getHmenvironmentList({ hidden: 0 })
      this.loadData()
    },
    loadData(pageNo = this.pageData.pageNo) {
      getHmhttpservicePageList({
        ...this.queryData,
        ...this.pageData,
        pageNo,
      }).then((res) => {
        if (res.data.length === 0 && pageNo > 1) {
          this.loadData(pageNo - 1)
          return
        }
        this.tableData = res.data.map((item) => {
          const newSettings = item.settingList.map((setting) => {
            if (item.authType !== "NONE") {
              setting.params = setting.json ? JSON.parse(setting.json) : []
            }
            return setting
          })
          return {
            ...item,
            settingList: newSettings,
          }
        })
        this.total = res.totalCount
        this.pageData = {
          pageSize: res.pageSize,
          pageNo: res.pageNo,
        }
      })
    },

    handleReset() {
      this.queryData = {}
      this.loadData(1)
    },

    handleCreate(command) {
      if (command === "service") {
        this.$refs.HttpServiceForm.open(undefined, () => {
          this.loadData(1)
          this.$message.success("操作成功")
        })
      }
    },

    handleEdit(record) {
      this.$refs.HttpServiceForm.open(cloneDeep(record), () => {
        this.loadData()
        this.$message.success("操作成功")
      })
    },

    handleDelete(record) {
      deleteHmhttpservice([record.id]).then((res) => {
        this.loadData()
        this.$message.success("操作成功")
      })
    },
    getEnvActive(item) {
      if (item.type === "CLOUD") {
        return true
      }
      const envItem = this.envConfigList.find((i) => i.key === item.env)
      return envItem && envItem.hidden === 0
    },
    getEnvName(item) {
      if (item.type === "CLOUD") {
        return `${item.instanceName}（${item.envName}）`
      }
      const envItem = this.envConfigList.find((i) => i.key === item.env)
      return envItem.name
    },

    /**
     * 导出
     * @param {*} record
     */
    async handleExport(record) {
      const res = await getHmhttpserviceExport({
        id: record.id,
      })
      await exportAppDataFromJson({
        data: res,
        key: record.key,
        ext: "hm_service",
      })

      setTimeout(() => {
        this.$message.success("导出成功")
      }, 1500)
    },

    /**
     * 导入
     * @param {*} file
     */
    async handleHttpRequest(file) {
      const formData = new FormData()
      formData.append("file", file.file)
      await postHmhttpserviceImport(formData)
      this.$message.success("导入成功")
      this.loadData(1)
    },
  },
}
</script>

<style lang="scss" scoped>
.dymIcon {
  font-size: 20px;
  margin-right: 6px;
  vertical-align: text-bottom;
  color: #409eff;
}
.ds-table {
  &_env-title {
    line-height: 32px;
    font-weight: bold;
  }

  &_env-info .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
    display: flex;

    &:last-child {
      margin-bottom: 0;
    }

    ::v-deep label {
      width: 100px;
      color: #99a9bf;
      line-height: 24px;
      font-size: 12px;
      flex: none;
    }
    ::v-deep .el-form-item__content {
      line-height: 24px;
      font-size: 12px;
      flex: 1;
      word-break: break-all;
    }
  }
}
</style>
